package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            String line = readLine();
            System.out.println(line);

            String method;//请求方式
            String uri;//抽象路径
            String protocol;//协议版本

            String[] str = line.split("\\s");
            method = str[0];
            uri = str[1];
            protocol = str[2];

            Map<String, String> headers = new HashMap<>();
            while (true) {
                line = readLine();
                if (line.isEmpty()) {
                    break;
                }
                System.out.println("消息头" + line);
                String[] data = line.split(":\\s");
                headers.put(data[0], data[1]);

            }
            System.out.println("headers:" + headers);//V3





        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String  readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char cur = 'a', pre = 'a';
        while ((d = in.read()) != -1) {
            cur = (char)d;
            if (pre == 13 && cur == 10) {
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();

    }
}
